package com.jinlejia.erp.ui.mine.transfer;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.jinlejia.erp.R;
import com.jinlejia.erp.bean.TransferBean;
import com.jinlejia.erp.databinding.ActivityTransferApplyHierarchyBinding;
import com.weight.CustomToast;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

/**
 * 异动申请-职务/层级
 */
public class TransferApplyHierarchyActivity extends AppCompatActivity {
    private TransferBean transferBean;
    private Boolean lower;
    private String userLevel;
    private String level;
    private ActivityTransferApplyHierarchyBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_transfer_apply_hierarchy);
        binding.setEvent(this);
        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    private void initData() {
        transferBean = (TransferBean) getIntent().getSerializableExtra("bean");
        lower = getIntent().getBooleanExtra("lower", false);
        transferBean.setTransferType("1");
        if (lower && ("diaobumenjinsheng".equals(transferBean.getUserbdTypeCode())
                || "jinsheng".equals(transferBean.getUserbdTypeCode())
                || "pingdiao".equals(transferBean.getUserbdTypeCode())
                || "zhuanshiyong".equals(transferBean.getUserbdTypeCode())
                || "zhuanzheng".equals(transferBean.getUserbdTypeCode()))) {//有下属人员且异动类型选的调部门+晋升、晋升、平调、转试用、转正时出现下属人员转移
            binding.llPersonneltransferall.setVisibility(View.VISIBLE);
        } else {
            binding.llPersonneltransferall.setVisibility(View.GONE);
            transferBean.setTransferType("0");//没有下属人员
        }
    }

    private void initView() {
        formatStr(binding.tvBusnesss, "*");
        formatStr(binding.tvSuperiors, "*");
        formatStr(binding.tvTrainingLogo, "*");
        binding.rgMain.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.sell_radio) {
                transferBean.setTransferType("1");
            } else if (checkedId == R.id.rent_radio) {
                transferBean.setTransferType("2");
            }
        });

    }

    private Intent mIntent;

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_business:
                //异动后职务
                mIntent = new Intent(TransferApplyHierarchyActivity.this, TransferCheckActivity.class);
                mIntent.putExtra("type", "2");
                mIntent.putExtra("checkId", checkId);
                startActivityForResult(mIntent, 2001);
                break;
            case R.id.llTrainingLogo:
                //带训标识
                mIntent = new Intent(TransferApplyHierarchyActivity.this, TransferCheckActivity.class);
                mIntent.putExtra("type", "4");
                mIntent.putExtra("checkId2", checkId2);
                startActivityForResult(mIntent, 2003);
                break;
            case R.id.ll_superior:
                //直属上级
                if (TextUtils.isEmpty(binding.tvBusiness.getText().toString())) {
                    CustomToast.showToast(TransferApplyHierarchyActivity.this, "请选择异动后的职务", 1500);
                } else {
                    mIntent = new Intent(TransferApplyHierarchyActivity.this, TransferApplySearchActivity.class);
                    mIntent.putExtra("newDutyCode", transferBean.getNewDutyCode().toString());
                    mIntent.putExtra("type", "1");
                    startActivityForResult(mIntent, 2002);
                }
                break;
            case R.id.bt_pre:
                //上一步
                releaceData();
                finish();
                break;
            case R.id.bt_next:
                //下一步
                checkData();
                break;
            case R.id.back_btn:
                finish();
                break;
        }
    }

    /**
     * 清空本页bean存储数据
     */
    private void releaceData() {
        transferBean.setNewDutyCode("");//异动后职务code
        transferBean.setNewDutyName("");//异动后职务name
        transferBean.setLeaderStoreCode("");//直属上级共享店code
        transferBean.setLeaderStoreName("");//直属上级共享店名称
        transferBean.setNewLeaderPin("");//直属上级pin
        transferBean.setLeaderDutyName("");//直属上级职务名称
        transferBean.setTransferType("");//下属人员转移
    }

    private void checkData() {
        if (TextUtils.isEmpty(binding.tvBusiness.getText().toString())) {
            CustomToast.showToast(TransferApplyHierarchyActivity.this, "请选择异动后的职务", 1500);
        } else if (binding.llSuperiorall.getVisibility() == View.VISIBLE && TextUtils.isEmpty(binding.tvSuperior.getText().toString())) {
            CustomToast.showToast(TransferApplyHierarchyActivity.this, "请选择直属上级", 1500);
        } else if (binding.substituteTrainingLogo.getVisibility() == View.VISIBLE && TextUtils.isEmpty(binding.tvTrainingLogobutton.getText().toString())){
            CustomToast.showToast(TransferApplyHierarchyActivity.this, "请选择标识", 1500);
        }else if (checkLevel(Integer.parseInt(userLevel), Integer.parseInt(level), transferBean.getUserbdTypeCode())) {
            Intent intent = new Intent();
            intent.setClass(TransferApplyHierarchyActivity.this, TransferApplyDepartmentActivity.class);
            intent.putExtra("bean", transferBean);
            intent.putExtra("userLevel", userLevel);
            intent.putExtra("level", level);
            intent.putExtra("newTrainingFlag",String.valueOf(binding.tvTrainingLogobutton.getTag()));
            startActivity(intent);
        }
    }

    private void formatStr(TextView view, String word) {
        String tmp = "<font color=\"red\">" + word + "</font>";
        String str = view.getText().toString().replace(word, tmp);
        //Html.fromHtml(str)
        view.setText(Html.fromHtml(str));
    }

    private int checkId = -1;
    private int checkId2 = -1;//带训标识复现ID

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 2001) {
                binding.tvBusiness.setText(data.getStringExtra("name"));
                checkId = data.getIntExtra("checkId", -1);
                userLevel = data.getStringExtra("userLevel");//异动前职务等级
                level = data.getStringExtra("level");//异动后职务等级
                transferBean.setNewDutyCode(data.getStringExtra("code"));
                transferBean.setNewDutyName(data.getStringExtra("name"));
                if ("chengshizongjingli".equals(transferBean.getNewDutyCode())) {//异动后质素是城市总经理，则没有直属上级
                    transferBean.setNewLeaderPin("");
                    binding.llSuperiorall.setVisibility(View.GONE);
                } else {
                    binding.llSuperiorall.setVisibility(View.VISIBLE);
                }


            } else if (requestCode == 2002) {
                binding.tvSuperior.setText(data.getStringExtra("userName"));
                transferBean.setNewLeaderPin(data.getStringExtra("pin"));
                transferBean.setLeaderStoreCode(data.getStringExtra("shareStoreCode"));//直属上级共享店code
                transferBean.setLeaderStoreName(data.getStringExtra("shareStoreName"));//直属上级共享店名称
                transferBean.setLeaderDutyName(data.getStringExtra("dutyName"));//直属上级职务名称

                //合作人异动平调和晋升后，第二步选择上级后应隐藏下属人员转移选项
            }else if (requestCode==2003){
                binding.tvTrainingLogobutton.setText(data.getStringExtra("name"));
                binding.tvTrainingLogobutton.setTag(data.getStringExtra("code"));
                checkId2 = data.getIntExtra("checkId", -1);
            }
        }
    }

    /**
     * @param oldLevel       异动前职务等级
     * @param newLevel       异动后职务等级
     * @param userbdTypeCode 异动类型
     */
    private boolean checkLevel(int oldLevel, int newLevel, String userbdTypeCode) {
        if (!"diaogang".equals(userbdTypeCode) && 0 == oldLevel) {//
            CustomToast.showToast(TransferApplyHierarchyActivity.this, "非地产人员只能选择调岗,请返回上一步", 1500);
            return false;
        } else if ("diaogang".equals(userbdTypeCode) && 0 != oldLevel) {
            CustomToast.showToast(TransferApplyHierarchyActivity.this, "非地产人员只能选择调岗,请返回上一步", 1500);
            return false;
        } else if (oldLevel != 1 && "jinsheng".equals(userbdTypeCode) && oldLevel >= newLevel) {
            CustomToast.showToast(TransferApplyHierarchyActivity.this, "晋升后职务等级必须高于原职务等级", 1500);
            return false;
        } else if ("pingdiao".equals(userbdTypeCode) && oldLevel != newLevel) {
            CustomToast.showToast(TransferApplyHierarchyActivity.this, "平调后职务等级必须与原职务等级相同", 1500);
            return false;
        } else if ("diaobumenjinsheng".equals(userbdTypeCode) && oldLevel >= newLevel) {
            CustomToast.showToast(TransferApplyHierarchyActivity.this, "晋升后职务等级必须高于原职务等级", 1500);
            return false;
        }else if ("jiangzhi".equals(userbdTypeCode) && oldLevel < newLevel) {
            CustomToast.showToast(TransferApplyHierarchyActivity.this, "降职后职务等级必须低于原职务等级", 1500);
            return false;
        }else if ("diaobumenjiangzhi".equals(userbdTypeCode) && oldLevel < newLevel) {
            CustomToast.showToast(TransferApplyHierarchyActivity.this, "降职后职务等级必须低于原职务等级", 1500);
            return false;
        }
        return true;
    }


    @Subscriber
    public void onEvent(TransferApplySuccessEvent event) {
        if (event.getResult() == 0) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        releaceData();
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
